package GUILayer;

import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import CtrLayer.DiscountCtr;

public class DiscountGUI {

	private JPanel panel, firstPanel;
	private static DiscountCtr discountCtr = new DiscountCtr();

	public DiscountGUI() {}
	
	
	
	// Panel for Customer Discounts
	private JPanel makeCustomerDiscountPanel() {
		
		HashMap<String,Double> customerDiscounts = discountCtr.getCustomerDiscounts();
		
		int size = customerDiscounts.size();
		
		String[] columnNames = {"Customer type","Discount (%)", "Delete"};
		Object[][] data = new Object[size][columnNames.length];
		
		int i=0;
		
		for(String key : customerDiscounts.keySet())
		{
			data[i][0] = key.toString();
			data[i][1] = customerDiscounts.get(key).toString();
			data[i][2] = Boolean.FALSE;
			i++;
		}
		
		
		
		
		DefaultTableModel dtm = new DefaultTableModel(data,columnNames){
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col){		// <-- override for non-editable cells
				return (col==2);
			}
			
			public Class<?> getColumnClass(int col) {
				if (col == 2)  return Boolean.class;
				return super.getColumnClass(col);
			}
		};
		
		
		final JTable table = new JTable(dtm);
		JScrollPane tablePane = new JScrollPane(table);
		
		tablePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		tablePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		tablePane.setPreferredSize(new Dimension(250,280));
		
		
		
		TableColumnModel tcm = table.getColumnModel();
		tcm.getColumn(0).setPreferredWidth(60);  
		tcm.getColumn(1).setPreferredWidth(40);
		tcm.getColumn(2).setPreferredWidth(5);
		
		
		JPanel tablePanel = new JPanel();
		tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.X_AXIS));
		
		JButton addCustDiscButton = new JButton("Add new customer discount");
		
		addCustDiscButton.setAlignmentY(JButton.TOP_ALIGNMENT);
		tablePane.setAlignmentY(JButton.TOP_ALIGNMENT);
		
		tablePanel.add(addCustDiscButton);
		tablePanel.add(tablePane);
		
		
		
		
		
		
		table.getTableHeader().addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent ev)
			{
				int col = table.columnAtPoint(ev.getPoint());
				
				if(col == 2)
				{
					int selected = getSelectedOptions(table);
					if(selected==0)
					{
						JOptionPane.showConfirmDialog(null, "You didn't selected any discounts","Info",JOptionPane.CLOSED_OPTION);
					}
					else
					{
						int answer = JOptionPane.showConfirmDialog(null, "Do you want to permanent delete "+ selected +" discount(s) ?","Confirm delete discounts",JOptionPane.YES_NO_OPTION);
						if(answer == JOptionPane.YES_OPTION)
						{
							deleteSelectedProducts(table);
						}
					}
				}
			}
		});
		
		
		table.addMouseListener(new MouseAdapter(){
			
			public void mouseClicked(MouseEvent e)
			{
				if(e.getClickCount()==2)
				{
					JTable target = (JTable)e.getSource();
					int row = target.getSelectedRow();
					String customerType = (String)target.getModel().getValueAt(row, 0);
					discountFrame("Edit "+customerType+" Discount",customerType);
				}
			}
			
		});
		
		
		
		addCustDiscButton.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent arg0) {
				JPanel inputPanel = new JPanel();
				inputPanel.setLayout(new GridLayout(0,2));
				
				JLabel customerLabel = new JLabel("Customer type");
				JLabel discountLabel = new JLabel("Discount (%)");
				
				JTextField customerValue = new JTextField(10);
				JTextField discountValue = new JTextField(10);
				
				inputPanel.add(customerLabel);
				inputPanel.add(customerValue);
				
				inputPanel.add(discountLabel);
				inputPanel.add(discountValue);
				
				
				int answear = JOptionPane.showConfirmDialog(null,inputPanel, "Add Customer Discount", JOptionPane.OK_CANCEL_OPTION);
				if(answear == JOptionPane.OK_OPTION)
				{
					String customerV = customerValue.getText();
					double discountV = 0;
					
					try{ discountV = Double.parseDouble(discountValue.getText()); }
					catch(Exception ex){}
					
					discountCtr.addCustomerDiscount(customerV, discountV);
					
					reAddGrid();
				}
			}
		});
		
		
		
		return tablePanel;		
	}
	
	
	public void discountFrame(String title,String customerType)
	{
		JPanel inputPanel = new JPanel();
		inputPanel.setLayout(new GridLayout(0,2));
		
		JLabel customerLabel = new JLabel("Customer type");
		JLabel discountLabel = new JLabel("Discount (%)");
		
		JLabel customerValue = new JLabel(customerType);
		JTextField discountValue = new JTextField(10);
		
		discountValue.setText(String.valueOf(discountCtr.getCustomerDiscount(customerType)));
		
		
		inputPanel.add(customerLabel);
		inputPanel.add(customerValue);
		
		inputPanel.add(discountLabel);
		inputPanel.add(discountValue);
		
		
		int answear = JOptionPane.showConfirmDialog(null,inputPanel, title, JOptionPane.OK_CANCEL_OPTION);
		if(answear == JOptionPane.OK_OPTION)
		{
			String customerV = customerValue.getText();
			double discountV = 0;
			
			try{ discountV = Double.parseDouble(discountValue.getText()); }
			catch(Exception ex){}
			
			discountCtr.addCustomerDiscount(customerV, discountV);
			
			reAddGrid();
		}
	
	}
	
	
	
	public int getSelectedOptions(JTable table)
	{
		int count = 0;
		
		for(int i=0;i<table.getRowCount();i++)
		{
			if( (Boolean)table.getValueAt(i, 2) == true ) count++;
		}
		
		return count;
	}
	
	private void deleteSelectedProducts(JTable table)
	{
		for(int i=0;i<table.getRowCount();i++)
		{
			if( (Boolean)table.getValueAt(i, 2) == true )
			{
				String custType = (String)table.getValueAt(i, 0);
				discountCtr.removeCDiscount(custType);
			}
		}
		reAddGrid();
	}
	
	
	
	
	
	// Panel for Pickup Discount
	private JPanel makePickupDiscountPanel() {

		int emptyDelimitator = 10;
		
		JLabel pickUpDisc = new JLabel("Discount (%)");
		final JTextField pickUpDiscountValue = new JTextField(1);
		
		pickUpDiscountValue.setText(String.valueOf(discountCtr.getPickupDiscount()));
		
		JPanel errMess = new JPanel();
		final JLabel errors = new JLabel();
		errors.setForeground(Color.red);
		errMess.add(errors);

		
		JButton setPickupDiscButton = new JButton("Set");
		setPickupDiscButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) 
			{
				String error = "";
				double pickupDisc = 0; 
				try{ pickupDisc = Double.parseDouble(pickUpDiscountValue.getText());} 
				catch(Exception ex) {}
				
				if (pickupDisc == 0)  error = "Invalid number or field is empty";
				if (error != "")  errors.setText(error);
				else 
				{
					errors.setText("");
					discountCtr.addPickupDiscount(pickupDisc);
					JOptionPane.showConfirmDialog(null, "Pickup discount was successfully changed", "Pickup Discount", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE);
				}
			}

		});
		
		
		
		JPanel addPanel = new JPanel();
		GridLayout grid = new GridLayout(0, 2);
		grid.setVgap(4);

		addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.X_AXIS));
		addPanel.add(pickUpDisc);
		addPanel.add(Box.createHorizontalStrut(emptyDelimitator));
		addPanel.add(pickUpDiscountValue);
		addPanel.add(Box.createHorizontalStrut(emptyDelimitator));
		addPanel.add(setPickupDiscButton);

		
		JPanel addPickupDiscMain = new JPanel();
		addPickupDiscMain.setLayout(new BoxLayout(addPickupDiscMain,BoxLayout.Y_AXIS));
		int sp = 8;
		addPickupDiscMain.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black),
						"Pick up Discount"), BorderFactory.createEmptyBorder(
						sp, sp, sp, sp)));

		addPickupDiscMain.add(addPanel);
		addPickupDiscMain.add(errMess);
		

		return addPickupDiscMain;
	}
	
	
	
	private void reAddGrid()
	{
		firstPanel.remove(2);
		firstPanel.add(makeCustomerDiscountPanel());
		firstPanel.revalidate();
	}
	
	

	
	//Method for Discount tab
	public JPanel makeDiscountTab() {
		panel = new JPanel();

		firstPanel = new JPanel();
		firstPanel.setLayout(new BoxLayout(firstPanel,BoxLayout.Y_AXIS));

		firstPanel.add(makePickupDiscountPanel());
		firstPanel.add(Box.createVerticalStrut(20));
		firstPanel.add(makeCustomerDiscountPanel());

		panel.add(firstPanel);

		return panel;
	}

}
